import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlOutputVisitor;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor;
import com.alibaba.druid.sql.dialect.postgresql.visitor.PGOutputVisitor;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
/*
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
*/
public class SqlFormat {
    public static void main(String[] args) throws IOException {
        String format = format(sql, DbType.mysql);
        System.out.println(format);
        /*
        File file = new File("sql.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(format.getBytes(StandardCharsets.UTF_8));
         */
    }

    private static String format(String sql, DbType dbType){
        if (dbType == null){
            throw new RuntimeException("have not selected db type!");
        }
        SQLStatementParser sqlStatementParser = SQLParserUtils.createSQLStatementParser(sql, dbType);
        List<SQLStatement> sqlStatements = sqlStatementParser.parseStatementList();

        StringBuilder sb = new StringBuilder();
        SQLASTOutputVisitor visitor;
        switch (dbType){
            case postgresql: visitor = new PGOutputVisitor(sb);
            break;
            case mysql: visitor = new MySqlOutputVisitor(sb);
            break;
            case oracle: visitor = new OracleOutputVisitor(sb);
            break;
            default:
                visitor = new SQLASTOutputVisitor(sb);
        }

        for (SQLStatement statement : sqlStatements){
            statement.accept(visitor);
        }
        return sb.toString();
    }

    private static String sql = "select * from test";

}